package com.anpxd.erpad.ui

import android.content.Intent
import android.text.TextUtils
import com.anpxd.baselibrary.utils.AppManager
import com.anpxd.erpad.App
import com.anpxd.erpad.R
import com.anpxd.erpad.net.ApiFactory
import com.anpxd.erpad.net.ErpApi
import com.anpxd.ewalker.utils.toast
import com.gg.baseproject.Composers
import kotlinx.android.synthetic.main.activity_login.*

/**
 *  Creator : GG
 *  Time    : 2017/11/10
 *  Mail    : gg.jin.yu@gmail.com
 *  Explain : 登陆页
 */
class LoginActivity : BaseActivity() {

    private var mExitTime: Long = 0
    private val VALUE_EXIT_TIME: Long = 2000

    private lateinit var name: String
    private lateinit var password: String

    override fun getLayoutRes(): Int = R.layout.activity_login

    override fun initArguments() {

    }

    override fun initTitle() {
    }

    override fun initView() {

        login_tv.setOnClickListener {
            name = name_edit.text.toString()
            password = pwd_edit.text.toString()
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) {



                ApiFactory.getErpApi()
                        .login(accountName = name, accountPassword = password)
                        .compose(Composers.handleError())
                        .subscribe({

                            toast("登录成功")
                            App.instance.setUser(it)
                            startActivity(Intent(this, MainActivity::class.java))

                            ApiFactory.getErpApi()
                                    .shopList()
                                    .compose(Composers.handleError())
                                    .subscribe({
                                        App.instance.setShop(it[0])
                                        //登录成功保存一下, 后续可能使用
                                        App.instance.userName = name
                                        App.instance.passsWord = password
                                        finish()

                                    }, {})

                        }, {})//带参数的 才能够捕获异常
            } else {
                toast("帐号和密码不能为空")
            }
        }
    }

    override fun initData() {

    }


    override fun onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > VALUE_EXIT_TIME) {
            toast(R.string.exit_toast)
            mExitTime = System.currentTimeMillis()
        } else {
            AppManager.getInstance().finishActivity()
        }
    }

}